/*
Copyright  2018 Blockchain Technology and Application Joint Lab, Fintech Research Center of ISCAS.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */
import {Meteor} from 'meteor/meteor';
import Deasync from 'deasync';
import {CopyrightCertificates} from './copyright_certificates/copyright_certificates';
import {RegisterUser} from "./register_user/register_user";
Meteor.methods({
    //获取当前用户
    'account.currentUser'() {
        return CurUser;
    },
    //设置当前用户
    'account.setCurrentUser'(cusr) {
        CurUser = cusr;
        return CurUser;
    },
    //更新版权信息
    'certificate.update'(info){
        if(!info.txid)
            throw new Meteor.Error('transaction_info was invalid');
        else{
            // To wait until copyright certificate register successes
            Deasync.loopWhile(() => CopyrightCertificates.find({certificate_number: info.txid}).fetch().length  == 0);
            // To wait some seconds
            CopyrightCertificates.update({certificate_number: info.txid}, {$set: {status: info.status, block_timestamp: info.block_timestamp}});
        }
    },
    //插入版权信息
    'certificate.insert'(info){
        CopyrightCertificates.insert(info);
    },
    //统计版权个数
    'certificate.count'() {
        return CopyrightCertificates.find({}).count()
    },
    //插入注册用户信息
    'registerUser.insert'(info){
        RegisterUser.insert(info)
    },
    //更新注册用户信息
    'registerUser.update'(info){
        RegisterUser.update({account_address:info.account_address},{$set:info})
    },
    //更新注册用户信息 注销状态
    'registerUser.destroy'(addr){
        RegisterUser.update({account_address:addr},{$set:{status: false}})
    },
    //判断用户是否存在
    'registerUser.exist'(phone){
        let user = RegisterUser.findOne({'phone':phone})
        return user != undefined && user.status == true
    }
});
